package com.tkjt.pms.modules.repos.service.impl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tkjt.pms.common.entity.*;
import com.tkjt.pms.common.utils.*;
import com.tkjt.pms.common.vos.TkIndexReportVO;
import com.tkjt.pms.impt.common.KpiConsts;
import com.tkjt.pms.impt.common.KpiImportUtils;
import com.tkjt.pms.impt.vos.*;
import com.tkjt.pms.modules.common.mapper.*;
import com.tkjt.pms.modules.common.service.*;
import com.tkjt.pms.modules.kpiadmin.mapper.DataGridMapper;
import com.tkjt.pms.modules.kpiadmin.vo.DatagridVO;
import com.tkjt.pms.modules.repos.vo.*;
import com.tkjt.pms.modules.tkindexvaluerule.entity.TkIndexValueRule;
import com.tkjt.pms.modules.tkindexvaluerule.mapper.TkIndexValueRuleMapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tkjt.pms.modules.repos.common.IndexInfoTreeParam;
import com.tkjt.pms.modules.repos.mapper.IndexRepoMapper;
import com.tkjt.pms.modules.repos.service.IndexRepoService;

@Service
@Transactional
public class IndexRepoServiceImpl implements IndexRepoService {
	@Autowired
	private IndexRepoMapper indexRepoMapper;
	@Autowired
	private TkIndexInfoMapper tkIndexInfoMapper;
	@Autowired
	private TkIndexValueAttrsMapper tkIndexValueAttrsMapper;
	@Autowired
	private TkIndexConfigMapper tkIndexConfigMapper;
	@Autowired
    private TkIndexValueRuleMapper tkIndexValueRuleMapper;
	@Autowired
	TkIndexInfoService tkIndexInfoService;
	@Autowired
	TkIndexValueService tkIndexValueService;
	@Autowired
	TkIndexValueMapper tkIndexValueMapper;
	@Autowired
	TkIndexValueAttrsService tkIndexValueAttrsService;
	@Autowired
	PMSCommonMapper commonMapper;
	@Autowired
	ISysUserDepartService sysUserDepartService;
	@Autowired
	ISysUserService sysUserService;
	@Autowired
	ISysDepartService sysDepartService;
	@Autowired
	TkDepartGroupService tkDepartGroupService;
    @Autowired
    TkIndexValueImportMapper tkIndexValueImportMapper;
	@Autowired
	DataGridMapper dataGridMapper;
	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	TkIndexValueAuditMapper tkIndexValueAuditMapper;
	@Autowired
	TkIndexValueImportService tkIndexValueImportService;
	@Autowired
	private TkIndexValueAdjustMapper tkIndexValueAdjustMapper;

	@Override
	public Result<?> indexTree(IndexInfoTreeParam treeParam) {
		if (StringUtils.isEmpty(treeParam.getIndexGroup())) {
			return Result.error("参数缺失！");
		}
		String indexGroup = treeParam.getIndexGroup();
		IndexInfoTreeVO indexInfoTreeVO = new IndexInfoTreeVO();
		indexInfoTreeVO.setCode(indexGroup);
		indexInfoTreeVO.setKey(indexGroup);
		indexInfoTreeVO.setType("indexGroup");
		if ("C".equals(indexGroup)) {
			indexInfoTreeVO.setTitle("一线单位");
		} else {
			indexInfoTreeVO.setTitle("养康本部");
		}
		Map<String, Object> param = new HashMap<>();
		param.put("indexGroup", indexGroup);
		param.put("type", "index");
		List<IndexInfoTreeVO> childList = indexRepoMapper.selectValueAndCodeByTypeAndGroup(param);
		for (int i = 0; i < childList.size(); i++) {
			param = new HashMap<>();
			param.put("indexGroup", indexGroup);
			param.put("type", "indexValue");
			param.put("indexCode", childList.get(i).getCode());
			List<IndexInfoTreeVO> childChildList = indexRepoMapper.selectValueAndCodeByTypeAndGroup(param);
			childList.get(i).setChildren(childChildList);
		}
		indexInfoTreeVO.setChildren(childList);
		return Result.ok(indexInfoTreeVO);
	}

	@Override
	public Result<?> delNode(IndexInfoTreeVO indexInfoTreeVO) {
		String type = indexInfoTreeVO.getType();
		if (StringUtils.isEmpty(type)) {
			return Result.error("参数缺失！");
		}
		String key = indexInfoTreeVO.getKey();
		if (StringUtils.isEmpty(key)) {
			return Result.error("参数缺失！");
		}
		String indexGroup = "";
		String code = "";
		if (type.equals("index")) {
			indexGroup = key.substring(0, 1);
			code = key.substring(2);
		} else {
			code = key;
		}
		Map<String, Object> param = new HashMap<>();
		param.put("code", code);
		param.put("type", type);
		param.put("indexGroup", indexGroup);
		indexRepoMapper.delNode(param);
		return Result.ok();
	}

	@Override
	public Result<?> addNode(IndexInfoTreeAddVO indexInfoTreeAddVO) {
		String type = indexInfoTreeAddVO.getType();
		if (StringUtils.isEmpty(type)) {
			return Result.error("参数缺失！");
		}
		String parentKey = indexInfoTreeAddVO.getParentKey();
		if (StringUtils.isEmpty(parentKey)) {
			return Result.error("参数缺失！");
		}
		String title = indexInfoTreeAddVO.getTitle();
		if (StringUtils.isEmpty(title)) {
			return Result.error("参数缺失！");
		}
		String indexGroup = "";
		Map<String,Object> existParam = new HashMap<>();
		if (type.equals("index")) {
			existParam.put("indexStatus","1");
			existParam.put("indexName",title);
			indexGroup = parentKey;
			existParam.put("indexGroup",indexGroup);
			List<TkIndexInfo> list = indexRepoMapper.selectInfosByAttrsParam(existParam);
			if (list.size() > 0) {
				return Result.error("指标名已存在！");
			}
			TkIndexInfo tkIndexInfo = new TkIndexInfo();
			tkIndexInfo.makeInitialData();
			tkIndexInfo.setIndexGroup(indexGroup);
			tkIndexInfo.setIndexCode(UUID.randomUUID().toString().replace("-", "").substring(0, 7));
			tkIndexInfo.setIndexName(title);
			String indexValueCode = UUID.randomUUID().toString().replace("-", "").substring(0,14);
			tkIndexInfo.setIndexValueCode(indexValueCode);
			tkIndexInfo.setIndexValueName("");
			tkIndexInfoMapper.insert(tkIndexInfo);
			/**
			 * 只新增指标，没有数据项，因此属性无法添加，无法分组，默认分配个数据项，给对应数据项归属部门属性
			 * 下次添加该指标对应数据项时做update操作
			 */
			List<TkIndexValueAttrs> attrs = new ArrayList<>();
			TkIndexValueAttrs tempIndexValueAttrs = new TkIndexValueAttrs();
			tempIndexValueAttrs.setIndexValueCode(indexValueCode);
			tempIndexValueAttrs.setAttrCode("orgGroup");
			tempIndexValueAttrs.setAttrValue(indexGroup);
			attrs.add(tempIndexValueAttrs);

			IndexInfoAttrsAddVO indexInfoAttrsAddVO = new IndexInfoAttrsAddVO();
			indexInfoAttrsAddVO.setType("indexValue");
			indexInfoAttrsAddVO.setKey(indexValueCode);
			indexInfoAttrsAddVO.setAttrs(attrs);
			modifyAttrs(indexInfoAttrsAddVO);
			return Result.ok();
		} else if (type.equals("indexValue")) {
			indexGroup = parentKey.substring(0, 1);
			String indexCode = parentKey.substring(2);
			existParam.put("indexStatus","1");
			existParam.put("indexCode",title);
			existParam.put("indexValueName",indexCode);
			existParam.put("indexGroup",indexGroup);
			List<TkIndexInfo> list = indexRepoMapper.selectInfosByAttrsParam(existParam);
			if (list.size() > 0) {
				return Result.error("指标名已存在！");
			}
			/**
			 * 第一次添加指标默认生成的数据项只有是否禁用和数据项归属部门属性，数据项名称是空字符串，根据空字符串查找做更新操作
			 */
			Map<String,Object> tempInfoParam = new HashMap<>();
			tempInfoParam.put("indexGroup",indexGroup);
			tempInfoParam.put("indexCode",indexCode);
			TkIndexInfo tempInfo = indexRepoMapper.selectTempInfosByParam(tempInfoParam);
			String newIndexValueCode = UUID.randomUUID().toString().replace("-", "").substring(0,14);
			if (tempInfo != null) {
				tempInfo.setIndexValueName(title);
				tkIndexInfoMapper.updateById(tempInfo);
				TkIndexValueAttrs tempIndexValueAttrs = new TkIndexValueAttrs();
				tempIndexValueAttrs.setIndexValueCode(tempInfo.getIndexValueCode());
				tempIndexValueAttrs.setAttrCode("orgGroup");
				tempIndexValueAttrs.setAttrValue(indexGroup);
				List<TkIndexValueAttrs> attrs = new ArrayList<>();
				attrs.add(tempIndexValueAttrs);
				IndexInfoAttrsAddVO indexInfoAttrsAddVO = new IndexInfoAttrsAddVO();
				indexInfoAttrsAddVO.setType("indexValue");
				indexInfoAttrsAddVO.setKey(tempInfo.getIndexValueCode());
				indexInfoAttrsAddVO.setAttrs(attrs);
				modifyAttrs(indexInfoAttrsAddVO);
			} else {
				Map<String, Object> param = new HashMap<>();
				param.put("indexGroup", indexGroup);
				param.put("indexCode", indexCode);
				param.put("indexStatus", "1");
				List<String> indexNames = indexRepoMapper.selectIndexNameByIndexCode(param);
				TkIndexInfo tkIndexInfo = new TkIndexInfo();
				tkIndexInfo.makeInitialData();
				tkIndexInfo.setIndexGroup(indexGroup);
				tkIndexInfo.setIndexCode(indexCode);
				tkIndexInfo.setIndexName(indexNames.size() > 0 ? indexNames.get(0) : "");
				tkIndexInfo.setIndexValueCode(newIndexValueCode);
				tkIndexInfo.setIndexValueName(title);
				tkIndexInfoMapper.insert(tkIndexInfo);
			}
			if (indexInfoTreeAddVO.getAttrs() != null && indexInfoTreeAddVO.getAttrs().size() > 0) {
				IndexInfoAttrsAddVO indexInfoAttrsAddVO = new IndexInfoAttrsAddVO();
				indexInfoAttrsAddVO.setType(type);
				indexInfoAttrsAddVO.setKey(newIndexValueCode);
				indexInfoAttrsAddVO.setAttrs(indexInfoTreeAddVO.getAttrs());
				return modifyAttrs(indexInfoAttrsAddVO);
			}

			return Result.ok();
		} else {
			return Result.error("权限暂未开放！");
		}
	}

	@Override
	public Result<?> queryAttrs(IndexInfoTreeVO indexInfoTreeVO) {

		String key = indexInfoTreeVO.getKey();
		if (StringUtils.isEmpty(key)) {
			return Result.error("参数缺失！");
		}
		String type = indexInfoTreeVO.getType();
		if (StringUtils.isEmpty(type)) {
			return Result.error("参数缺失！");
		}
		if (!type.equals("indexValue")) {
//			return Result.error("权限暂未开放！");
			return Result.ok("指标无属性！");
		}

		JSONArray attrsArray = null;
		{
			QueryWrapper<TkIndexConfig> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(TkIndexConfig::getConfigCode, type+"Attrs");
			TkIndexConfig indexConfigAttrs = tkIndexConfigMapper.selectOne(queryWrapper);
			if (null == indexConfigAttrs) {
				return Result.ok(new ArrayList<Map<String, Object>>());
			}
			attrsArray = (JSONArray) JSONObject.parse(indexConfigAttrs.getConfigBody());
		}
		if (null == attrsArray || attrsArray.size() <= 0) {
			Result.ok(new ArrayList<Map<String, Object>>());
		}

		List<Map<String, Object>> selectedAttrValueList = null;

		Map<String, Object> param = new HashMap<>();
		if (type.equals("index")) {
			String[] levelIndexs = key.split("@");
			String indexGroup = levelIndexs[0];
			param.put("indexGroup", indexGroup);
			if (levelIndexs.length > 2) {
				param.put("code", levelIndexs[2]);
				param.put("parentCode", levelIndexs[1]);
			} else {
				param.put("code", levelIndexs[1]);
				param.put("parentCode", null);
			}
			selectedAttrValueList = indexRepoMapper.queryIndexAttrs(param);
		} else if (type.equals("indexValue")) {
			param.put("code", key);
			selectedAttrValueList = indexRepoMapper.queryIndexValueAttrs(param);
		}

		{
			Map<String, Object> selectedAttrValues = new HashMap<String, Object>();
			for (int i = 0; i < selectedAttrValueList.size(); i++) {
				Map<String, Object> selectedValues = selectedAttrValueList.get(i);
				selectedAttrValues.put((String) selectedValues.get("attrCode"), selectedValues.get("attrValue"));
			}
			for (int index = 0; index < attrsArray.size(); index++) {
				JSONObject tempObj = (JSONObject) attrsArray.get(index);
				tempObj.put("key", key);
				Object selectedValue = selectedAttrValues.get(tempObj.getString("attrCode"));
				if (null == selectedValue) {
					tempObj.put("attrValue", "");
				} else {
					tempObj.put("attrValue", selectedValue);
				}
				tempObj.remove("attrOptions");
			}
		}

		return Result.ok(attrsArray);

	}

	@Override
	public Result<?> modifyAttrs(IndexInfoAttrsAddVO indexInfoAttrsAddVO) {
		String type = indexInfoAttrsAddVO.getType();
		if (StringUtils.isEmpty(type)) {
			return Result.error("参数缺失！");
		}
		String key = indexInfoAttrsAddVO.getKey();
		if (StringUtils.isEmpty(key)) {
			return Result.error("参数缺失！");
		}
		String indexGroup = "";
		String code = "";
		if (type.equals("index")) {
			indexGroup = key.substring(0, 1);
			code = key.substring(2);
		} else {
			code = key;
		}
		Map<String, Object> param = new HashMap<>();
		param.put("code", code);
		param.put("type", type);
		param.put("indexGroup", indexGroup);
		indexRepoMapper.delAttrs(param);
		List<TkIndexValueAttrs> attrs = indexInfoAttrsAddVO.getAttrs();
		if (type.equals("index")) {
			return Result.error("权限暂未开放！");
			// todo 改变指标下所有数据项属性为相同数据，不合理
			/*
			 * QueryWrapper<TkIndexInfo> infoQueryWrapper = new QueryWrapper<>();
			 * infoQueryWrapper.lambda().eq(TkIndexInfo::getIndexGroup,indexGroup);
			 * infoQueryWrapper.lambda().eq(TkIndexInfo::getIndexStatus,"1");
			 * infoQueryWrapper.lambda().eq(TkIndexInfo::getIndexCode,code);
			 * List<TkIndexInfo> infos = tkIndexInfoMapper.selectList(infoQueryWrapper);
			 * for(TkIndexInfo info : infos){
			 * for (int i = 0 ; i < attrs.size() ; i++){
			 * attrs.get(i).setIndexValueCode(info.getIndexValueCode());
			 * tkIndexValueAttrsMapper.insert(attrs.get(i));
			 * }
			 * }
			 */
		} else if (type.equals("indexValue")) {
			boolean noIndexStatus = true;
			for (int i = 0; i < attrs.size(); i++) {
				if(attrs.get(i).getAttrCode().equals("indexStatus")){
					noIndexStatus = false;
				}
				attrs.get(i).setIndexValueCode(code);
				tkIndexValueAttrsMapper.insert(attrs.get(i));
			}
			//前端添加数据项时，没有给是否禁用属性值，默认赋个值
			if(noIndexStatus){
				TkIndexValueAttrs tkIndexValueAttrs = new TkIndexValueAttrs();
				tkIndexValueAttrs.setAttrCode("indexStatus");
				tkIndexValueAttrs.setAttrValue("1");
				tkIndexValueAttrs.setIndexValueCode(code);
				tkIndexValueAttrsMapper.insert(tkIndexValueAttrs);
			}

		} else {
			return Result.error("权限暂未开放！");
		}
		return Result.ok();
	}

	@Override
	public Result<?> listAttrs(IndexInfoTreeVO IndexInfoTreeVO) {
		String type = IndexInfoTreeVO.getType();
		QueryWrapper<TkIndexConfig> queryWrapper = new QueryWrapper<>();
		if (StringUtils.isNotEmpty(type)) {
			queryWrapper.lambda().eq(TkIndexConfig::getConfigCode, type);
		} else {
			Set<String> configCodes = new HashSet<String>();
			configCodes.add("indexAttrs");
			configCodes.add("indexValueAttrs");
			queryWrapper.lambda().in(TkIndexConfig::getConfigCode, configCodes);
		}
		List<TkIndexConfig> list = tkIndexConfigMapper.selectList(queryWrapper);
		Map<String, Object> resultMap = new HashMap<>();
		for (TkIndexConfig tkIndexConfig : list) {
			if (StringUtils.isNotEmpty(tkIndexConfig.getConfigBody())) {
				resultMap.put(tkIndexConfig.getConfigCode(), JSONObject.parse(tkIndexConfig.getConfigBody()));
			} else {
				resultMap.put(tkIndexConfig.getConfigCode(), new ArrayList<>());
			}
		}
		return Result.ok(resultMap);
	}

	@Override
	public Result<?> orderIndexs(IndexInfoTreeVO indexInfoTreeVO) {
		int orderNum = 0;
		if ("C".equals(indexInfoTreeVO.getKey())) {
			orderNum = 10000;
		} else {
			orderNum = 20000;
		}
		List<IndexInfoTreeVO> childList = indexInfoTreeVO.getChildren();
		for (IndexInfoTreeVO child : childList) {
			String parentType = child.getType();
			List<IndexInfoTreeVO> childChildList = child.getChildren();
			if(childChildList == null){
				return Result.error("数据项不能作为指标层级！");
			}
			for (IndexInfoTreeVO childChild : childChildList) {
				String childType = childChild.getType();
				if(childChild.getChildren() != null){
					return Result.error("目前不支持二级指标！");
				}
				if (childType.equals(parentType)) {
					return Result.error("目前不支持二级指标！");
				}
				if(!childChild.getCode().contains(child.getCode())){
					return Result.error("目前数据项不支持跨指标层级排序！");
				}
			}
		}

		for (IndexInfoTreeVO child : childList) {
			List<IndexInfoTreeVO> childChildList = child.getChildren();
			for (IndexInfoTreeVO childChild : childChildList) {
				String indexValueCode = childChild.getCode();
				orderNum++;
				TkIndexInfo tkIndexInfo = new TkIndexInfo();
				tkIndexInfo.setIndexValueCode(indexValueCode);
				tkIndexInfo.setIndexValueOrder(orderNum);
				tkIndexInfoMapper.updateIndexInfoOrderByParam(tkIndexInfo);
			}
		}
		return Result.ok();
	}

	@Override
	public Result<?> indexRuleDatagrid(IndexValueRuleVO indexValueRuleVO) {
		String searchText = indexValueRuleVO.getSearchText();
		Integer pageNo = indexValueRuleVO.getPageNo();
		Integer pageSize = indexValueRuleVO.getPageSize();
		if (pageNo == null) {
			return Result.error("参数缺失！");
		}
		if (pageSize == null) {
			return Result.error("参数缺失！");
		}
		Map<String,Object> param = new HashMap<>();
		if(StringUtils.isNotEmpty(searchText)){
			param.put("searchText",searchText);
		}
		param.put("min", (pageNo - 1) * pageSize);
		param.put("max", pageSize);
		List<TkIndexValueRule> list = indexRepoMapper.indexRuleDatagridPageList(param);
		int count = indexRepoMapper.indexRuleDatagridPageCount(param);
		Page<TkIndexValueRule> finalPage = new Page<TkIndexValueRule>(pageNo,pageSize);
		finalPage.setTotal(count);
		finalPage.setCurrent(pageNo);
		finalPage.setSize(pageSize);
		int pages = count / pageSize;
		if (count % pageSize > 0) {
			pages += 1;
		}
		finalPage.setPages(pages);
		finalPage.setRecords(list);
		return Result.ok(finalPage);
	}

	@Override
	public Result<?> whichDataList() {
		QueryWrapper<TkIndexConfig> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(TkIndexConfig::getConfigCode, "whichData");
		TkIndexConfig indexConfigAttrs = tkIndexConfigMapper.selectOne(queryWrapper);
		if (null == indexConfigAttrs) {
			return Result.ok(new ArrayList<Map<String, Object>>());
		}
		JSONArray attrsArray = (JSONArray) JSONObject.parse(indexConfigAttrs.getConfigBody());
		Map<String,Object> resultMap = new HashMap<>();
		resultMap.put("whichData",attrsArray);
		return Result.ok(resultMap);
	}

    @Override
    public Result<?> searchIndexValue(IndexValueRuleVO indexValueRuleVO) {
        String searchText = indexValueRuleVO.getSearchText();
        Map<String,Object> param = new HashMap<>();
        if(StringUtils.isNotEmpty(searchText)){
            param.put("searchText",searchText);
        }
        List<Map<String,Object>> list = indexRepoMapper.searchIndexValue(param);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("indexValueCode",list);
        return Result.ok(resultMap);
    }

    @Override
    public Result<?> indexRuleSave(TkIndexValueRuleVO tkIndexValueRuleVO) {
        if(StringUtils.isEmpty(tkIndexValueRuleVO.getIndexValueCode())){
            return Result.error("参数缺失！");
        }
        if(StringUtils.isEmpty(tkIndexValueRuleVO.getIndexValueRule())){
            return Result.error("参数缺失！");
        }
        if(StringUtils.isEmpty(tkIndexValueRuleVO.getIndexValueRuleCn())){
            return Result.error("参数缺失！");
        }
		if(StringUtils.isNotEmpty(tkIndexValueRuleVO.getIndexDepart()) && tkIndexValueRuleVO.getIndexDepart().length() == 9){
			return Result.error("请选择指标部门！");
		}
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(StringUtils.isEmpty(tkIndexValueRuleVO.getId())){
			TkIndexValueRule tkIndexValueRule = new TkIndexValueRule();
			BeanUtils.copyProperties(tkIndexValueRuleVO,tkIndexValueRule);
			tkIndexValueRule.setId(null);
			tkIndexValueRule.setCreateDate(new Date());
			tkIndexValueRule.setCreateBy(loginUser.getRealname());
			tkIndexValueRuleMapper.insert(tkIndexValueRule);
		}else{
			TkIndexValueRule tkIndexValueRule = new TkIndexValueRule();
			BeanUtils.copyProperties(tkIndexValueRuleVO,tkIndexValueRule);
			tkIndexValueRule.setUpdateDate(new Date());
			tkIndexValueRule.setUpdateBy(loginUser.getRealname());
			tkIndexValueRuleMapper.updateById(tkIndexValueRule);
		}

        return Result.ok();
    }

	/**
	 * 处理指一线按部门标值
	 */
    @Override
	public void processCIndexData(String indexGroup,String dataType,String indexYearMonth,List<UpdateCIndexVo> results) throws Exception{
		QueryWrapper<TkIndexValueImport> importQueryWrapper = new QueryWrapper<>();
		importQueryWrapper.lambda().eq(TkIndexValueImport::getIndexYearMonth,indexYearMonth);
		importQueryWrapper.lambda().likeRight(TkIndexValueImport::getIndexDepart,indexGroup);
		tkIndexValueImportMapper.delete(importQueryWrapper);
		for (UpdateCIndexVo indexVo : results) {
			List<KpiIndexValueVo> indexValues = indexVo.getIndexValues();
			Field[] field = indexVo.getClass().getDeclaredFields();
			for(int j=0 ; j<field.length ; j++){
				String fieldName = field[j].getName();
				String firstLetter = fieldName.substring(0, 1).toUpperCase();
				String getter = "get" + firstLetter + fieldName.substring(1);
				Method method = null;
				method = indexVo.getClass().getMethod(getter, new Class[] {});
				String orgCode = fieldName.substring(1);
				if(fieldName.startsWith("V")){
					List<KpiIndexBaseDataVo> indexData = (List<KpiIndexBaseDataVo>)method.invoke(indexVo, new Object[] {});
					updateIndexValueEntity(dataType, indexYearMonth,orgCode,indexValues,indexData);
				}
			}
		}
	}
	/**
	 * 处理指本部按部门标值
	 */
    @Override
    public void processGIndexData(String indexGroup,String dataType,String indexYearMonth,List<UpdateGIndexVo> results) throws Exception{
		QueryWrapper<TkIndexValueImport> importQueryWrapper = new QueryWrapper<>();
		importQueryWrapper.lambda().eq(TkIndexValueImport::getDataType,dataType);
		importQueryWrapper.lambda().eq(TkIndexValueImport::getIndexYearMonth,indexYearMonth);
		importQueryWrapper.lambda().likeRight(TkIndexValueImport::getIndexDepart,indexGroup);
		tkIndexValueImportMapper.delete(importQueryWrapper);
    	for (UpdateGIndexVo indexVo : results) {
			List<KpiIndexValueVo> indexValues = indexVo.getIndexValues();
			Field[] field = indexVo.getClass().getDeclaredFields();
			for(int j=0 ; j<field.length ; j++){
				String fieldName = field[j].getName();
				String firstLetter = fieldName.substring(0, 1).toUpperCase();
				String getter = "get" + firstLetter + fieldName.substring(1);
				Method method = null;
				method = indexVo.getClass().getMethod(getter, new Class[] {});
				String orgCode = fieldName.substring(1);
				if(fieldName.startsWith("V")){
					List<KpiIndexBaseDataVo> indexData = (List<KpiIndexBaseDataVo>)method.invoke(indexVo, new Object[] {});
					updateIndexValueEntity(dataType,indexYearMonth, orgCode, indexValues,indexData);
				}
			}
		}
	}

	@Override
	public Result<?> confirmImportData(TkIndexValueImport tkIndexValueImport) {
		QueryWrapper<TkIndexValueImport> importQueryWrapper = new QueryWrapper<>();
		importQueryWrapper.lambda().eq(TkIndexValueImport::getIndexYearMonth,tkIndexValueImport.getIndexYearMonth());
		importQueryWrapper.lambda().eq(TkIndexValueImport::getDataType,tkIndexValueImport.getDataType());
		importQueryWrapper.lambda().eq(TkIndexValueImport::getIndexValueStatus,"0");
		List<TkIndexValueImport> tkIndexValueImports = tkIndexValueImportMapper.selectList(importQueryWrapper);
		for(TkIndexValueImport itemImport : tkIndexValueImports){
			TkIndexValue tkIndexValue = new TkIndexValue();
			String indexYear = EsDateUtils.getIndexYear(tkIndexValueImport.getIndexYearMonth());
			QueryWrapper<TkIndexValueAdjust> adjustQueryWrapper = new QueryWrapper<>();

			adjustQueryWrapper.eq("index_depart", itemImport.getIndexDepart());
			adjustQueryWrapper.eq("index_value_code", itemImport.getIndexValueCode());
			if(StringUtils.isNotEmpty(itemImport.getDataType())){
				adjustQueryWrapper.eq("data_type", itemImport.getDataType());
			}
			adjustQueryWrapper.eq("year", indexYear);
			List<TkIndexValueAdjust> adjusts = tkIndexValueAdjustMapper.selectList(adjustQueryWrapper);
			Double oneValue = itemImport.getMTotal();
			if (null != oneValue && isHaveAdjustData(adjusts, "mTotal") == true && !oneValue.isNaN()) {
				tkIndexValue.setMTotal(oneValue);
			}
			oneValue = itemImport.getM01();
			if (null != oneValue && isHaveAdjustData(adjusts, "m01") == true && !oneValue.isNaN()) {
				tkIndexValue.setM01(oneValue);
			}
			oneValue = itemImport.getM02();
			if (null != oneValue && isHaveAdjustData(adjusts, "m02") == true && !oneValue.isNaN()) {
				tkIndexValue.setM02(oneValue);
			}
			oneValue = itemImport.getM03();
			if (null != oneValue && isHaveAdjustData(adjusts, "m03") == true && !oneValue.isNaN()) {
				tkIndexValue.setM03(oneValue);
			}
			oneValue = itemImport.getM04();
			if (null != oneValue && isHaveAdjustData(adjusts, "m04") == true && !oneValue.isNaN()) {
				tkIndexValue.setM04(oneValue);
			}
			oneValue = itemImport.getM05();
			if (null != oneValue && isHaveAdjustData(adjusts, "m05") == true && !oneValue.isNaN()) {
				tkIndexValue.setM05(oneValue);
			}
			oneValue = itemImport.getM06();
			if (null != oneValue && isHaveAdjustData(adjusts, "m06") == true && !oneValue.isNaN()) {
				tkIndexValue.setM06(oneValue);
			}
			oneValue = itemImport.getM07();
			if (null != oneValue && isHaveAdjustData(adjusts, "m07") == true && !oneValue.isNaN()) {
				tkIndexValue.setM07(oneValue);
			}
			oneValue = itemImport.getM08();
			if (null != oneValue && isHaveAdjustData(adjusts, "m08") == true && !oneValue.isNaN()) {
				tkIndexValue.setM08(oneValue);
			}
			oneValue = itemImport.getM09();
			if (null != oneValue && isHaveAdjustData(adjusts, "m09") == true && !oneValue.isNaN()) {
				tkIndexValue.setM09(oneValue);
			}
			oneValue = itemImport.getM10();
			if (null != oneValue && isHaveAdjustData(adjusts, "m10") == true && !oneValue.isNaN()) {
				tkIndexValue.setM10(oneValue);
			}
			oneValue = itemImport.getM11();
			if (null != oneValue && isHaveAdjustData(adjusts, "m11") == true && !oneValue.isNaN()) {
				tkIndexValue.setM11(oneValue);
			}
			oneValue = itemImport.getM12();
			if (null != oneValue && isHaveAdjustData(adjusts, "m12") == true && !oneValue.isNaN()) {
				tkIndexValue.setM12(oneValue);
			}
			QueryWrapper<TkIndexValue> indexValueWrapper = new QueryWrapper<>();
			indexValueWrapper.lambda().eq(TkIndexValue::getIndexValueCode,itemImport.getIndexValueCode());
			indexValueWrapper.lambda().eq(TkIndexValue::getDataType,itemImport.getDataType());
			indexValueWrapper.lambda().eq(TkIndexValue::getIndexScorer,itemImport.getIndexScorer());
			indexValueWrapper.lambda().eq(TkIndexValue::getIndexDepart,itemImport.getIndexDepart());
			tkIndexValueMapper.update(tkIndexValue,indexValueWrapper);
		}
		return Result.ok();
	}

	public boolean isHaveAdjustData(List<TkIndexValueAdjust> adjusts, String which) {
		boolean sign = true;
		for (TkIndexValueAdjust item : adjusts) {
			if (which.equals(item.getWhich())) {
				sign = false;
			}
		}
		return sign;
	}

	private void updateIndexValueEntity(String dataType,String indexYearMonth, String indexOrgCode, List<KpiIndexValueVo> indexValues, List<KpiIndexBaseDataVo> indexDatas) {
		SysDepart depart = sysDepartService.getOne(new QueryWrapper<SysDepart>().lambda().eq(SysDepart::getOrgCode,indexOrgCode));
		List<SysUserDepart> userDeparts = sysUserDepartService.list(new QueryWrapper<SysUserDepart>().lambda().eq(SysUserDepart::getDepId,depart.getId()));
		for(SysUserDepart userDepart : userDeparts){
			SysUser scorer =sysUserService.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getId,userDepart.getUserId()));
				updateIndexValueEntityCommonWay(dataType,indexYearMonth,indexOrgCode,indexValues,indexDatas,scorer);

		}
	}

	private void updateIndexValueEntityCommonWay(String dataType,String indexYearMonth,String indexOrgCode, List<KpiIndexValueVo> indexValues, List<KpiIndexBaseDataVo> indexDatas,SysUser scorer){
		String yearMonth = EsDateUtils.getIndexYearMonth(new Date());
		String year = yearMonth.substring(0,4);
		QueryWrapper<TkDepartGroup> groupQueryWrapper = new QueryWrapper<>();
		groupQueryWrapper.lambda().eq(TkDepartGroup::getDepartAttr,"ATRV0000");
		List<TkDepartGroup> groups = tkDepartGroupService.list(groupQueryWrapper);
		List<String> vitralOrgCodes = new ArrayList<>();
		for(TkDepartGroup tkDepartGroup : groups){
			vitralOrgCodes.add(tkDepartGroup.getIndexDepart());
		}
		String[] dataTypes = {"budget","kpi"};
		for(String itemDataType : dataTypes){
			for (int index = 0; index < indexValues.size(); index++) {
				KpiIndexValueVo ivvo = indexValues.get(index);
				String indexValueCode = ivvo.getCode();
				QueryWrapper<TkIndexValueAttrs> attrWrapper = new QueryWrapper<>();
				attrWrapper.lambda().eq(TkIndexValueAttrs::getIndexValueCode,indexValueCode);
				attrWrapper.lambda().eq(TkIndexValueAttrs::getAttrCode,"indexAttr");
				TkIndexValueAttrs tkIndexValueAttrs = tkIndexValueAttrsMapper.selectOne(attrWrapper);
				if(tkIndexValueAttrs.getAttrValue().equals(InfoAttrUtil.MU_BIAO_ZHI) && !dataType.equals(itemDataType)){
					continue;
				}
				KpiIndexBaseDataVo iData = null;
				if (index >= indexDatas.size()) {
					//
					iData = new KpiIndexBaseDataVo();
					iData.setM01("0.0");
					iData.setM02("0.0");
					iData.setM03("0.0");
					iData.setM04("0.0");
					iData.setM05("0.0");
					iData.setM06("0.0");
					iData.setM07("0.0");
					iData.setM08("0.0");
					iData.setM09("0.0");
					iData.setM10("0.0");
					iData.setM11("0.0");
					iData.setM12("0.0");
				} else {
					iData = indexDatas.get(index);
				}

				// 格式化 传入值
				{
					Map<String, Object> beanMap = EsJsonUtils.bean2Map(iData);
					Set<String> keys = new HashSet<String>(beanMap.keySet());
					boolean insertSign = false;
					for (String key : keys) {
						String valueStr = (String) beanMap.get(key);
						if(StringUtils.isNotEmpty(valueStr)){
							insertSign = true;
						}
					}
					if(!insertSign){
						continue;
					}
					for (String key : keys) {
						String valueStr = (String) beanMap.get(key);
						valueStr = KpiImportUtils.formatValueStr(valueStr);
						beanMap.put(key, valueStr);
					}
					iData = (KpiIndexBaseDataVo) EsJsonUtils.map2Bean(beanMap, KpiIndexBaseDataVo.class);
				}

				TkIndexValueImport entity = null;
				{
					Map<String, Object> beanStrMap = EsJsonUtils.bean2Map(iData);
					Map<String, Object> beanDoubleMap = new HashMap<String, Object>();
					Set<Map.Entry<String, Object>> entries = beanStrMap.entrySet();
					for(Map.Entry<String, Object> entry : entries) {
						beanDoubleMap.put(entry.getKey(), 1.0*Double.valueOf((String)entry.getValue()));
					}
					beanDoubleMap.put("MTotal", beanDoubleMap.get("mTotal"));
					entity = (TkIndexValueImport)EsJsonUtils.map2Bean(beanDoubleMap, TkIndexValueImport.class);
				}
				if(null == entity) {
					entity = new TkIndexValueImport();
				}

				entity.setDataType(itemDataType);
				entity.setIndexValueCode(indexValueCode);
				entity.setIndexValueStatus("0");
				entity.setIndexScorer(scorer.getUsername());
				entity.setIndexDepart(indexOrgCode);
				entity.setIndexYearMonth(indexYearMonth);
				entity.setCreateBy("admin");
				entity.setCreateDate(new Date());
				entity.setUpdateBy("admin");
				entity.setUpdateDate(new Date());

				tkIndexValueImportMapper.insert(entity);
			}

		}

	}

	/**
	 * 目标实际值导入列表查询
	 * @return
	 */
	@Override
	public Result<?> kaFillDatagrid(DatagridVO datagridVO, String noVirtual, String dataType) {
		String indexGroup = datagridVO.getIndexGroup();
		String yearMonth = datagridVO.getIndexYearMonth();
		if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isEmpty(yearMonth)) {
			yearMonth = EsDateUtils.getIndexYearMonth(new Date());
		}
		Integer pageNo = datagridVO.getPageNo();
		if(pageNo == null){
			return Result.error("参数缺失");
		}
		Integer pageSize = datagridVO.getPageSize();
		if(pageSize == null){
			return Result.error("参数缺失");
		}
		Map<String,Object> param = new HashMap<>();
		param.put("min", (pageNo - 1) * pageSize);
		param.put("max", pageSize);
		QueryWrapper<TkIndexValueImport> importQueryWrapper = new QueryWrapper<>();
		if(indexGroup != null){
			String orgGroup = OrgGroupUtil.changeToCG(indexGroup);
			param.put("orgGroup",orgGroup);
			if("C".equals(orgGroup)){
				importQueryWrapper.lambda().likeRight(TkIndexValueImport::getIndexDepart,"A01A01A01A");
			}else{
				importQueryWrapper.lambda().likeRight(TkIndexValueImport::getIndexDepart,"A01A01A02A");
			}
		}
		param.put("indexValueEdit",datagridVO.getIndexValueEdit());
		if(datagridVO.getIndexCodes() != null && datagridVO.getIndexCodes().size() > 0){
			param.put("indexCodes",datagridVO.getIndexCodes());
		}
		if(datagridVO.getIndexTypes() != null && datagridVO.getIndexTypes().size() > 0){
			param.put("indexTypes",datagridVO.getIndexTypes());
		}
		param.put("dataType",dataType);
		//没有确认过的基础数据才展示
		importQueryWrapper.lambda().ne(TkIndexValueImport::getIndexValueStatus,"1");
		importQueryWrapper.lambda().eq(TkIndexValueImport::getDataType,dataType);
		int count = tkIndexValueImportService.count(importQueryWrapper);
		List<Map<String,Object>> result = new ArrayList<>();
		if(count > 0){
			result = indexRepoMapper.getImportIndexInfoMapByParamater(param);
			count = indexRepoMapper.getImportIndexInfoCountMapByParamater(param);
			dynamicColumnData(result,indexGroup,yearMonth,noVirtual,dataType);
		}
		Page<Map<String,Object>> finalPage = new Page<Map<String,Object>>(pageNo, pageSize);
		finalPage.setTotal(count);
		finalPage.setCurrent(pageNo);
		finalPage.setSize(pageSize);
		int pages = count / pageSize;
		if (count % pageSize > 0) {
			pages += 1;
		}
		finalPage.setPages(pages);
		finalPage.setRecords(result);
		return Result.ok(finalPage);
	}

	/**
	 * 动态列根据指标查询各个部门对应月份指标评分数据
	 * @param result
	 * @param indexGroup
	 * @param yearMonth
	 * @return
	 */
	public List<Map<String, Object>> dynamicColumnData(List<Map<String,Object>> result,String indexGroup,String yearMonth,String noVirtual,String dataType){
		Map<String,Object> orgParam = new HashMap<>();
		orgParam.put("noVirtual",noVirtual);
		orgParam.put("orgGroup",indexGroup);
		List<Map<String, Object>> orgs = dataGridMapper.getOrgAndUserByOrgGroup(orgParam);
		Map<String,Object> dataGridParam = new HashMap<>();
		String year = yearMonth.substring(0, 4);
		String month = yearMonth.substring(4);
		String[] roleCodes = {"ykgm","ykkpiowner"};
		List<String> userNames = sysUserMapper.selectUserNameByRoleCodes(roleCodes);
		userNames.add("system");
		Map<String,Object> yearMonthParam = new HashMap<>();
		yearMonthParam.put("year",year);
		Map<String,Object> indexYearMonthMap = indexRepoMapper.getIndexYearMonthByParam(yearMonthParam);
		String indexYearMonth = indexYearMonthMap != null ? indexYearMonthMap.get("indexYearMonth").toString() : "";
		dataGridParam.put("indexYearMonth",indexYearMonth);
		for ( int i = 0 ; i < result.size() ; i++ ){
			for (Map<String,Object> org : orgs ) {
				if(StringUtils.isEmpty(indexYearMonth)){
					result.get(i).put(org.get("code").toString(),null);
					result.get(i).put("indexValueStatus",null);
				}else{
					String orgColumn = org.get("code").toString();
					String indexDepart = orgColumn.substring(0,12);
					dataGridParam.put("indexDepart",indexDepart);
					if(orgColumn.length() > 12){
						dataGridParam.put("indexScorer",orgColumn.substring(12));
					}else{
						dataGridParam.put("indexScorer",null);
					}
					dataGridParam.put("indexValueCode",result.get(i).get("indexValueCode").toString());
					dataGridParam.put("month","m"+month);
					dataGridParam.put("dataType",dataType);
					Map<String, Object> monthValue = indexRepoMapper.getMonthIndexValueForParam(dataGridParam);
					if(monthValue == null){
						result.get(i).put("indexValueStatus",null);
						result.get(i).put(org.get("code").toString(),null);
					}else{
						result.get(i).put("indexValueStatus",monthValue.get("indexValueStatus").toString());
						result.get(i).put(org.get("code").toString(),DepartCode.formateForDouble(Double.valueOf(monthValue.get("m"+yearMonth.substring(4)).toString())));
					}
				}
			}
		}
		return result;
	}

	/**
	 * 目标值列表/绩效填报列表保存
	 * @param datagridVO
	 * @return
	 */
	@Override
	public Result<?> indexValueDataSave(DatagridVO datagridVO,String dataType) {
		String message = "";
		List<Map<String,Object>> values = datagridVO.getValues();
		String yearMonth = datagridVO.getIndexYearMonth();
		if(StringUtils.isEmpty(yearMonth)){
			return Result.error("参数缺失");
		}
		String indexGroup = datagridVO.getIndexGroup();
		if(StringUtils.isEmpty(indexGroup)){
			return Result.error("参数缺失");
		}
		QueryWrapper<TkIndexValueAudit> queryWrapperSdf = new QueryWrapper<>();
		queryWrapperSdf.lambda().eq(TkIndexValueAudit::getIndexGroup, "C".equals(indexGroup) ? "A01A01A01" : "A01A01A02");
		queryWrapperSdf.lambda().eq(TkIndexValueAudit::getIndexValueY, yearMonth.substring(0,4));
		queryWrapperSdf.lambda().eq(TkIndexValueAudit::getIndexValueM, yearMonth.substring(4));
		queryWrapperSdf.lambda().eq(TkIndexValueAudit::getDataType,dataType);
		TkIndexValueAudit indexValueAuditEntity = tkIndexValueAuditMapper.selectOne(queryWrapperSdf);
		if (indexValueAuditEntity != null) {
			if("2".equals(indexValueAuditEntity.getAuditStatus())){
				return Result.error("部门指标正在审核中，不允许修改");
			}else if("3".equals(indexValueAuditEntity.getAuditStatus())){
				return Result.error("部门指标已审核，不允许修改");
			}

		}
		String year = yearMonth.substring(0,4);
		String month = yearMonth.substring(4);
		if(values == null || values.size() == 0 ){
			return Result.ok(null);
		}
		Map<String,Object> param = new HashMap<>();
		param.put("orgGroup",indexGroup);
		List<String> orgCodes = dataGridMapper.getOrgCodeByOrgGroup(param);
		Map<String,Object> dataGridParam = new HashMap<>();
		Map<String,Object> yearMonthParam = new HashMap<>();
		yearMonthParam.put("year",year);
		Map<String,Object> indexYearMonthMap = indexRepoMapper.getIndexYearMonthByParam(yearMonthParam);
		String indexYearMonth = indexYearMonthMap != null ? indexYearMonthMap.get("indexYearMonth").toString() : "";
		if(StringUtils.isEmpty(indexYearMonth)){
			return Result.error("该年份数据不存在");
		}
		dataGridParam.put("indexYearMonth",indexYearMonth);
		for(Map<String,Object> rowData : datagridVO.getValues()){
			dataGridParam.put("indexValueCode",rowData.get("indexValueCode").toString());
			Iterator it = rowData.keySet().iterator();
			while (it.hasNext()) {
				String columData = it.next().toString();
				if(columData.length() >= 12){
					if(orgCodes.contains(columData.substring(0,12))){
						dataGridParam.put("indexDepart",columData.substring(0,12));
						if(columData.length() > 12){
							dataGridParam.put("indexScorer",columData.substring(12));
						}else{
							dataGridParam.put("indexScorer",null);
						}
						dataGridParam.put("month","m"+month);
						dataGridParam.put("dataType",dataType);
						Map<String, Object> importIonthValue = indexRepoMapper.getMonthIndexValueForParam(dataGridParam);
						double grade = TkGradeUtil.changeFormate(rowData.get(columData).toString());
						importIonthValue.put("m"+month,grade);
						TkIndexValueImport tkIndexValueImport = JSON.parseObject(JSON.toJSONString(importIonthValue), TkIndexValueImport.class);
						tkIndexValueImportMapper.updateById(tkIndexValueImport);
						if("1".equals(tkIndexValueImport.getIndexValueStatus())){
							Map<String, Object> monthValue = dataGridMapper.getMonthIndexValueForParam(dataGridParam);
							if(monthValue != null){
								monthValue.put("indexValueStatus",month.startsWith("0")? Integer.valueOf(month.substring(1)):Integer.valueOf(month));
								monthValue.put("m"+month,grade);
								TkIndexValue tkIndexValueEntity = JSON.parseObject(JSON.toJSONString(monthValue), TkIndexValue.class);
								tkIndexValueMapper.updateById(tkIndexValueEntity);
							}
						}
					}
				}
			}
		}
		return Result.ok("操作成功");
	}
}
